import 'package:cloud_medicine/components/tag.dart';
import 'package:cloud_medicine/components/user_avatar.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/doctor_api.dart';
import 'package:cloud_medicine/model/doctor_list.dart';
import 'package:cloud_medicine/pages/apply_doctor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class DoctorList extends StatefulWidget {
  @override
  _DoctorListState createState() => _DoctorListState();
}

class _DoctorListState extends State<DoctorList> {
  List<DoctorItem> _doctorList = [];
  bool showMoreLoading = false; // 上拉加载状态
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData();
      }
    });
    _loadData();
  }

  // 请求并更新数据
  _updateData() async {
    dynamic res = await getDoctorList_api('$backIP/doctor/list');
    setState(() {
      if (res['code'] == 0) {
        res['data'].forEach((dynamic doctor) {
          if (mounted) {
            setState(() {
              DoctorItem doctorItemModel = DoctorItem.init(doctor);
              _doctorList.add(doctorItemModel);
            });
          }
        });
      } else {
        errorToast(res['message']);
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose(); // 销毁监听器
    super.dispose();
  }

  // 加载更多数据
  Future<Null> _loadData() async {
    setState(() {
      showMoreLoading = true;
    });
    await _updateData();
    if (mounted) {
      setState(() {
        showMoreLoading = false;
      });
    }
  }

  // 下拉刷新，请求下一页的数据
  Future<Null> _refresh() async {
    _doctorList.clear(); // 清除当前状态数据
    await _updateData();
    Fluttertoast.showToast(
        msg: '刷新成功',
        backgroundColor: Colors.grey[300],
        textColor: Colors.lightBlueAccent);
    return;
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refresh,
      color: Theme.of(context).primaryColor,
      displacement: 40, // 指示器显示时距顶部位置
      child: ListView.builder(
          shrinkWrap: true,
          controller: _scrollController,
          itemCount: _doctorList.length + 1,
          itemBuilder: (context, index) {
            if (index == _doctorList.length) {
              return loadingWidget(false);
            } else {
              return Container(
                  height: 170,
                  color: Colors.white,
                  padding: EdgeInsets.all(8),
                  margin: EdgeInsets.only(bottom: 10),
                  child: Column(
                    children: <Widget>[
                      Container(
                        height: 100,
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 5),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            UserAvatar(
                              userID: _doctorList[index].authorBasicInfo.id,
                              imageStyle: 90,
                              avatar: _doctorList[index].authorBasicInfo.avatar,
                            ),
                            SizedBox(width: 20),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                    Text(_doctorList[index]
                                        .authorBasicInfo
                                        .realname),
                                    SizedBox(width: 10),
                                    Tag(
                                      text: getDoctorStatusInfo(
                                        _doctorList[index].status_id,
                                        'text',
                                      ),
                                      bgColor: getDoctorStatusInfo(
                                        _doctorList[index].status_id,
                                        'bgColor',
                                      ),
                                    )
                                  ],
                                ),
                                Container(
                                  width: 200,
                                  child: Text(
                                    '单位：${_doctorList[index].unit}',
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                Container(
                                  width: 200,
                                  child: Text(
                                    '简介：${_doctorList[index].abstract}',
                                    maxLines: 3,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                      Flex(
                        direction: Axis.vertical,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          RaisedButton(
                            child: Text('申请会诊'),
                            color: Colors.blue,
                            textColor: Colors.white,
                            onPressed: () {
                              Navigator.of(context).push(MaterialPageRoute(
                                  builder: (context) => ApplyDoctorPage(
                                        doctorID: _doctorList[index]
                                            .authorBasicInfo
                                            .id,
                                      )));
                            },
                          )
                        ],
                      )
                    ],
                  ));
            }
          }),
    );
  }
}
